package com.test.platform.dao;

import com.test.platform.model.PublishInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface PublishInfoMapper {
    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM publish_info p, (SELECT @rownum := 0) r " +
            "ORDER BY p.id DESC")
    List<PublishInfo> findAll();
    
    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM publish_info p, (SELECT @rownum := 0) r " +
            "WHERE p.owner LIKE CONCAT('%', #{owner}, '%') " +
            "ORDER BY p.id DESC")
    List<PublishInfo> findByOwner(@Param("owner") String owner);

    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM publish_info p, (SELECT @rownum := 0) r " +
            "WHERE p.name LIKE CONCAT('%', #{name}, '%') " +
            "ORDER BY p.id DESC")
    List<PublishInfo> findByName(@Param("name") String name);

    // 修改现有的方法为模糊查询
    @Select("SELECT (@rownum := @rownum + 1) AS displayId, p.* " +
            "FROM publish_info p, (SELECT @rownum := 0) r " +
            "WHERE p.owner LIKE CONCAT('%', #{owner}, '%') " +
            "AND p.name LIKE CONCAT('%', #{name}, '%') " +
            "ORDER BY p.id DESC")
    List<PublishInfo> findByOwnerAndName(@Param("owner") String owner, @Param("name") String name);

    @Select("SELECT MAX(id) FROM publish_info")
    Integer getMaxId();
    
    @Insert("INSERT INTO publish_info(owner, name, version, publisher, commit_id, change_log, status, title) " +
           "VALUES(#{owner}, #{name}, #{version}, #{publisher}, #{commitId}, #{changeLog}, #{status}, #{title})")
    @Options(useGeneratedKeys = true, keyProperty = "id")  // 添加这行以获取自增ID
    int insert(PublishInfo publishInfo);
    
    // 修改update方法，不再更改ID
    @Update("UPDATE publish_info SET " +
            "owner = #{owner}, " +
            "name = #{name}, " +
            "version = #{version}, " +
            "publisher = #{publisher}, " +
            "commit_id = #{commitId}, " +
            "change_log = #{changeLog}, " +
            "status = #{status}, " +
            "title = #{title} " +
            "WHERE id = #{id}")
    int update(PublishInfo publishInfo);  // 简化为直接使用 PublishInfo 对象

    // 删除不需要的updateToFirst方法
    
    // 删除不需要的reorderIds方法
    @Update({
        "SET @rank := 0;",
        "UPDATE publish_info SET id = (@rank := @rank + 1) ORDER BY id;"
    })
    void reorderIds();

    @Select("SELECT * FROM publish_info WHERE id = #{id}")
    PublishInfo findById(Integer id);

    @Delete("DELETE FROM publish_info WHERE id = #{id}")
    int deleteById(Integer id);

    /**
     * 根据owner和name删除发布信息
     */
    @Delete("DELETE FROM publish_info WHERE owner = #{owner} AND name = #{name}")
    int deleteByOwnerAndName(@Param("owner") String owner, @Param("name") String name);

    @Delete("DELETE FROM publish_info")
    int deleteAll();
}